#!/usr/bin/python
# -*- coding: utf-8 -*-

try:
	from urllib.request   import urlopen
	from urllib.error     import *
except ImportError:
	from urllib2          import *



from assis_const      import *
from assis_ui         import *
from assis_gui        import *
from assis_wxgui      import *
from lxml.etree       import * 

import lxml.html      as HTMLHandler
import shelve
import sys



class Connection :
	
	def __init__(self, server = DICT_ON_SERVER):
		
		self.server               = server
		self.SEARCH_OPT_SOUGHT    = SEARCH_OPT_SOUGHT
		self.SEARCH_OPT_LANGUAGES = SEARCH_OPT_LANGUAGES
		self.SEARCH_OPT_MODE      = SEARCH_OPT_MODE_PRE

	def consult(self, word):
		
		try:
			response = urlopen(self.server + \
			                   self.SEARCH_OPT_SOUGHT + word + \
						       self.SEARCH_OPT_LANGUAGES + \
						       self.SEARCH_OPT_MODE)
		except URLError as e:
			print(e.reason)
			
		rawdata = response.read().decode("utf-8")
		response.close()
		
		return rawdata
		
		
class Session (Connection) : 

	def __init__(self, word = "", local_dict = DICT_ON_LOCAL_HOST):
		
		Connection.__init__(self)
		self.last_sought = word
		self.history = shelve.open(local_dict, 'c')
		
	def get_last_dict(self): 
		
		return self.history.get(self.last_sought)
		
	def translate(self, word):
		
		self.last_sought = word
				
		if self.last_sought in self.history.keys():
			return self.get_last_dict()
			
		self.html = self.consult(self.last_sought)
		extract = Extract(self.html)
		self.history[self.last_sought] = extract.dct
		self.history.sync()
		
	def __del__(self):
		self.history.close()
		
		
class Extract :
		
	def __init__(self, html):
		
		self.html      = html
		self.doc       = HTMLHandler.fromstring(self.html)
		self.dct       = self.square_en2hu()
		
	def square_en2hu(self):
		
		dct = {}
		en  = []
		hu  = []

		for tag in self.doc.find_class("prop prop_content freetext"):
			if tag.tag in ["span"]: 
				if hu: 
					dct[tuple(en)] = tuple(hu)
					en[:] = []
					hu[:] = []
				en.append(tag.text_content())
				continue
			else:
				hu.append(tag.text_content().encode("utf-8", "ignore"))
				dct.update({tuple(en) : tuple(hu)})

   		return dct


if __name__ == "__main__":	
	
	
	ion	   = Session()
	
	wx_app = wxApplication(ion)
	wx_app.start()


